<template>
  <van-row class="post-container">
    <van-col span="24" class="form-container">
      <van-row :gutter="[20, 10]" style="text-align: center;">
        <van-col span="24">
          <van-notice-bar v-if="configStore.checkForbid" left-icon="volume-o" text="当前处于夜间休息时段，寻人寻物启事功能已关闭，请您谅解!" />
        </van-col>
        <van-col span="24" class="form-body">
          <van-form ref="formRef" :disabled="configStore.checkForbid">
            <van-field name="radio" label="类型" label-width="5rem" size="large" center>
              <template #input>
                <van-radio-group v-model="form.postType" :disabled="configStore.checkForbid" checked-color="#667eea"
                  direction="horizontal">
                  <van-radio name="0">寻人</van-radio>
                  <van-radio name="1">寻物</van-radio>
                </van-radio-group>
              </template>
            </van-field>

            <van-field v-model="form.lostName" size="large" label="名称/姓名" label-width="5rem" maxlength="16"
              :rules="[{ required: true, message: '请输入名称或姓名' }]" placeholder="请输入物品名称或人员姓名" />

            <van-field v-model="form.lostTime" size="large" label="丢失时间" label-width="5rem"
              :rules="[{ required: true, message: '请选择丢失时间' }]" readonly placeholder="请选择丢失时间"
              @click="showDatetimePicker" />
            <van-popup v-model:show="showPicker" round position="bottom">
              <van-picker-group title="丢失时间" :tabs="['选择日期', '选择时间']" next-step-text="下一步" @confirm="confirmDatetime"
                @cancel="showPicker = false">
                <van-date-picker v-model="pickerDate" />
                <van-time-picker v-model="pickerTime" />
              </van-picker-group>
            </van-popup>

            <van-field v-model="form.lostPlace" size="large" label="丢失地点" label-width="5rem" maxlength="50"
              :rules="[{ required: true, message: '请输入丢失地点' }]" placeholder="请输入丢失地点" />

            <van-field v-model="form.description" size="large" label="描述信息" label-width="5rem"
              :rules="[{ required: true, message: '请输入描述信息' }]" type="textarea" rows="4" maxlength="500" show-word-limit
              placeholder="请输入物品特征或人员外貌特征等信息" />

            <van-field v-model="form.contactPlace" size="large" label="联系地点" label-width="5rem" maxlength="50"
              :rules="[{ required: true, message: '请输入联系地点' }]" placeholder="请输入联系地点" />

            <van-field v-model="form.contactPhone" size="large" label="联系人电话" label-width="5rem" type="number"
              maxlength="11"
              :rules="[{ required: true, message: '请输入联系人电话' }, { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号' }]"
              placeholder="请输入联系人电话" />

            <van-button size="large" color="#667eea" block :disabled="configStore.checkForbid" @click="handleSubmit"
              style="margin-top: 10px">
              发布
            </van-button>
          </van-form>
        </van-col>
      </van-row>
    </van-col>
    <van-col span="24" class="history-link">
      <router-link to="/findPost/history">已发启事?这里查看结果</router-link>
    </van-col>
  </van-row>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import { getImpactType, getImpactCode } from '@/utils/auth'
import { useConfigStore } from '@/stores/config';
import { findPostAdd } from '@/api/findPost';

const router = useRouter();

const configStore = useConfigStore();

const isWechat = ref(false);
const formRef = ref(null);
const form = ref({
  postType: '0',
  lostName: '',
  lostTime: '',
  lostPlace: '',
  description: '',
  contactPlace: '',
  contactPhone: '',
  impactType: getImpactType(),
  impactCode: getImpactCode(),
});

const showPicker = ref(false);
const pickerDate = ref([]);
const pickerTime = ref([])

onMounted(() => {
  const userAgent = navigator.userAgent.toLowerCase();
  isWechat.value = userAgent.includes('micromessenger');
  const now = new Date();
  pickerDate.value = [now.getFullYear().toString(), (now.getMonth() + 1).toString(), now.getDate().toString()];
  pickerTime.value = [now.getHours().toString(), now.getMinutes().toString()];
  document.body.style.overflow = 'hidden';
});

onUnmounted(() => {
  document.body.style.overflow = '';
});

const showDatetimePicker = () => {
  if (configStore.checkForbid) return;
  showPicker.value = true;
};

const confirmDatetime = (value) => {
  form.value.lostTime = pickerDate.value.join('-') + ' ' + pickerTime.value.join(':');
  showPicker.value = false;
};

const handleSubmit = async () => {
  if (!formRef.value) return;
  try {
    await formRef.value.validate();
  } catch (errors) {
    console.error('表单校验失败:', errors);
    return;
  }
  findPostAdd(form.value).then(res => {
    showDialog({
      message: '发布成功',
      confirmButtonColor: '#667eea',
    }).then(() => {
      clearForm();
      router.push('/findPost/history');
    }).catch(() => { });
  })
};

const clearForm = () => {
  form.value = {
    postType: '0',
    lostName: '',
    lostTime: '',
    lostPlace: '',
    description: '',
    contactPlace: '',
    contactPhone: '',
    impactType: getImpactType(),
    impactCode: getImpactCode(),
  };
};
</script>

<style scoped>
.post-container {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 0px 20px;
  text-align: center;
  min-height: calc(100vh - 46px);
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.form-container {
  background-color: rgba(255, 255, 255, 1);
  border-radius: 16px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  padding: 15px;
}

.history-link {
  text-align: center;
}

.history-link a {
  color: #fff;
  font-size: 15px;
  text-decoration: none;
}
</style>
